﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.ObrigacoesPack
{
    [Serializable()]
    public class Obrigacoes : BusinessBase<Obrigacoes>
    {

        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private String _titulo = String.Empty;

        private String _periodo = String.Empty;

        private String _pagamento = String.Empty;

        private String _observacao = String.Empty;

        private String _descricao = String.Empty;

        private DateTime _dataCadastro = DateTime.Now;


        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public String Titulo
        {
            get
            {
                CanReadProperty("Titulo", true);
                return _titulo;
            }
            set
            {
                CanWriteProperty("Titulo", true);
                if (value == null) value = String.Empty;
                if (!_titulo.Equals(value))
                {
                    _titulo = value;
                    PropertyHasChanged("Titulo");
                }
            }
        }

        public String Periodo
        {
            get
            {
                CanReadProperty("Periodo", true);
                return _periodo;
            }
            set
            {
                CanWriteProperty("Periodo", true);
                if (value == null) value = String.Empty;
                if (!_periodo.Equals(value))
                {
                    _periodo = value;
                    PropertyHasChanged("Periodo");
                }
            }
        }

        public String Pagamento
        {
            get
            {
                CanReadProperty("Pagamento", true);
                return _pagamento;
            }
            set
            {
                CanWriteProperty("Pagamento", true);
                if (value == null) value = String.Empty;
                if (!_pagamento.Equals(value))
                {
                    _pagamento = value;
                    PropertyHasChanged("Pagamento");
                }
            }
        }

        public String Observacao
        {
            get
            {
                CanReadProperty("Observacao", true);
                return _observacao;
            }
            set
            {
                CanWriteProperty("Observacao", true);
                if (value == null) value = String.Empty;
                if (!_observacao.Equals(value))
                {
                    _observacao = value;
                    PropertyHasChanged("Observacao");
                }
            }
        }

        public String Descricao
        {
            get
            {
                CanReadProperty("Descricao", true);
                return _descricao;
            }
            set
            {
                CanWriteProperty("Descricao", true);
                if (value == null) value = String.Empty;
                if (!_descricao.Equals(value))
                {
                    _descricao = value;
                    PropertyHasChanged("Descricao");
                }
            }
        }

        public DateTime DataCadastro
        {
            get
            {
                CanReadProperty("DataCadastro", true);
                return _dataCadastro;
            }
            set
            {
                CanWriteProperty("DataCadastro", true);
                if (value == null) value = DateTime.Now;
                if (!_dataCadastro.Equals(value))
                {
                    _dataCadastro = value;
                    PropertyHasChanged("DataCadastro");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id.ToString().Trim().Replace("\"", "\\\"");
        }

        #endregion 

        #region Validation Rules
        private void AddCustomRules()
        {
            
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion 

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
        }


        public static bool CanGetObject()
        {
            return true;
        }

        public static bool CanAddObject()
        {
            return true;
        }

        public static bool CanEditObject()
        {
            return true;
        }

        public static bool CanDeleteObject()
        {
            return true;
        }
        #endregion

        #region Factory Methods
        private Obrigacoes() {  }

        public static Obrigacoes NewObrigacoes()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Obrigacoes");
            return DataPortal.Create<Obrigacoes>();
        }

        public static Obrigacoes GetObrigacoes(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Obrigacoes");
            return DataPortal.Fetch<Obrigacoes>(new Criteria(id));
        }

        public override Obrigacoes Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Obrigacoes");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Obrigacoes");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Obrigacoes");

            return base.Save();
        }

        public static void DeleteObrigacoes(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Obrigacoes");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;
            }
        }


        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                ExecuteFetch(cn, criteria);
            }//using
        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();
                    FetchChildren(dr);
                }
            }
        }

        private String GetFetchScript(Criteria criteria)
        {
            return "SELECT "
                 + "Id, "
                 + "Titulo, "
                 + "Periodo, "
                 + "Pagamento, "
                 + "Observacao, "
                 + "Descricao, "
                 + "DataCadastro "
                 + "FROM obrigacoestb "
                 + "WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;

            _id = new Guid(dr["Id"].ToString().Trim().Replace("\"", "\\\""));
            _titulo = dr.GetString("Titulo");
            _periodo = dr.GetString("Periodo");
            _pagamento = dr.GetString("Pagamento");
            _observacao = dr.GetString("Observacao");
            _descricao = dr.GetString("Descricao");
            _dataCadastro = dr.GetDateTime("DataCadastro");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();
                ExecuteInsert(cn);
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - Obrigacoestb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();
                cm.ExecuteNonQuery();
            }
        }

        private String GetInsertScript()
        {
            return "INSERT INTO obrigacoestb "
                +"( Id, Titulo, Periodo, Pagamento, Observacao, Descricao, DataCadastro ) "
                + " VALUES (\""
                + _id.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _titulo.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _periodo.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _pagamento.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _observacao.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _descricao.ToString().Trim().Replace("\"", "\\\"") + "\", \""
                + _dataCadastro.ToString("yyyy-MM-dd HH:mm:ss") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - Obrigacoestb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private String GetUpdateScript()
        {
            return "Update obrigacoestb set "
                    + "Titulo=\"" + _titulo.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Periodo=\"" + _periodo.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Pagamento=\"" + _pagamento.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Observacao=\"" + _observacao.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "Descricao=\"" + _descricao.ToString().Trim().Replace("\"", "\\\"") + "\", "
                    + "DataCadastro=\"" + _dataCadastro.ToString().Trim().Replace("\"", "\\\"") + "\" "
                                   
                    + "WHERE Id=\"" + _id.ToString().Trim().Replace("\"", "\\\"") + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - Obrigacoestb - Id: " + _id.ToString().Trim().Replace("\"", "\\\""));
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from obrigacoestb WHERE Id=\"" + criteria.Id.ToString().Trim().Replace("\"", "\\\"") + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}